import 'package:ffi/ffi.dart';
import 'package:flutter/cupertino.dart';
import 'package:window_example/tab/custom_tab_controller.dart';

class CustomerTabBar extends StatefulWidget {
  final List<Widget> tabs;
  final CustomerTabController controller;

  const CustomerTabBar(this.tabs, this.controller, {super.key});

  @override
  State<CustomerTabBar> createState() => _CustomerTabBarState();
}

class _CustomerTabBarState extends State<CustomerTabBar> {
  @override
  Widget build(BuildContext context) {
    debugPrint("tabs.length:${widget.tabs.length}");
    debugPrint("controller.length:${widget.controller.length}");
    assert(widget.tabs.length == widget.controller.length,
        "tabs.length must be equal to controller.length:[tabs.length:${widget.tabs.length}--controller.length:${widget.controller.length}]");
    return ListView.builder(
      itemCount: widget.tabs.length,
      itemBuilder: (BuildContext context, int index) {
        return GestureDetector(
          onTap: () {
            debugPrint("onTap:$index");
            widget.controller.changeIndex(index);
          },
          child: widget.tabs[index],
        );
      },
    );
  }
}

class CustomTabView extends StatefulWidget {
  final List<Widget> tabViews;
  final CustomerTabController controller;

  const CustomTabView(this.tabViews, this.controller, {super.key});

  @override
  State<CustomTabView> createState() => _CustomTabViewState();
}

class _CustomTabViewState extends State<CustomTabView> {
  int currentIndex = 0;

  @override
  void initState() {
    debugPrint("initState  widget.controller.addListener ");
    widget.controller.addListener(() {
      debugPrint("controller Listener ");
      debugPrint("controller Listener index${widget.controller.index} ");
      if (mounted) {
        setState(() {
          currentIndex = widget.controller.index;
        });
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    assert(widget.tabViews.length == widget.controller.length,
        "tabViews.length must Be equal to controller.length:[tabViews.length:${widget.tabViews.length}--controller.length${widget.controller.length}]");
    return (widget.tabViews.length == widget.controller.length &&
            widget.controller.length > 0)
        ? widget.tabViews[currentIndex]
        : const Text("Data mismatch");
  }
}
